package com.student.education.service.impl;

import com.github.pagehelper.PageHelper;
import com.student.education.common.CommonPage;
import com.student.education.entity.Exam;
import com.student.education.dao.ExamDao;
import com.student.education.service.ExamService;
import com.student.education.to.ExamQueryTo;
import com.student.education.vo.ExamQueryVo;
import com.student.education.vo.ExamVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 考试类型维护表(Exam)表服务实现类
 *
 * @author makejava
 * @since 2021-10-10 00:23:54
 */
@Service("examService")
public class ExamServiceImpl implements ExamService {
    @Resource
    private ExamDao examDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Exam queryById(Integer id) {
        return this.examDao.queryById(id);
    }


    /**
     * 新增数据
     *
     * @param exam 实例对象
     * @return 实例对象
     */
    @Override
    public int insert(ExamVo exam) {
        exam.setClassIds(StringUtils.join(exam.getClassId().toArray(), ","));
        return examDao.insert(exam);
    }

    /**
     * 修改数据
     *
     * @param exam 实例对象
     * @return 实例对象
     */
    @Override
    public int update(ExamVo exam) {
        exam.setClassIds(StringUtils.join(exam.getClassId().toArray(), ","));
        return examDao.update(exam);
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.examDao.deleteById(id) > 0;
    }

    @Override
    public CommonPage<ExamQueryTo> queryAll(ExamQueryVo vo) {
        if (vo.getPageUtil() != null) {
            PageHelper.startPage(vo.getPageUtil().getPageNumber(), vo.getPageUtil().getPageSize());
        }
        List<ExamQueryTo> list = examDao.queryAll(vo);
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setClassId(Arrays.asList(list.get(i).getClassIds().split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList()));
        }
        return CommonPage.restPage(list);
    }
}
